﻿import React, { useState } from "react";
import "./App.css";
import "./EpdCalculator.css";

function EpdCalculator() {
  const [selectedFile, setSelectedFile] = useState(null);
  const [extractedData, setExtractedData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showSolidFlooring, setShowSolidFlooring] = useState(true);
  const [showEngineeredFlooring, setShowEngineeredFlooring] = useState(true);
  const [showSolid2PlyFlooring, setShowSolid2PlyFlooring] = useState(true);
  const [recognizedDocumentType, setRecognizedDocumentType] = useState(null);
  // New state variables for epd2 checkboxes
  const [showMonolithicGlass, setShowMonolithicGlass] = useState(true);
  const [showLaminatedGlass, setShowLaminatedGlass] = useState(true);
  const [showSealedUnits, setShowSealedUnits] = useState(true);

  const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0]);
  };

  const processEpd = async () => {
    if (selectedFile) {
      setIsLoading(true);

      try {
        const recognizedDocumentType = await recognizeDocument(selectedFile);

        if (recognizedDocumentType === "epd1") {
          console.log("Processing EPD...");
          await new Promise((resolve) => setTimeout(resolve, 2000));
        } else if (recognizedDocumentType === "epd2") {
          console.log("Processing EPD...");
          await new Promise((resolve) => setTimeout(resolve, 2000));
        } else {
          console.log("Recognized document type:", recognizedDocumentType);
          await new Promise((resolve) => setTimeout(resolve, 2000));
        }

        const extractedData = await extractData(
          selectedFile,
          recognizedDocumentType
        );
        setExtractedData(extractedData);
      } catch (error) {
        console.error("Error processing document:", error);
      } finally {
        setIsLoading(false);
      }
    } else {
      alert("Please select a file first.");
    }
    const recognizedDocumentType = await recognizeDocument(selectedFile);
    setRecognizedDocumentType(recognizedDocumentType); // Update the state variable
  };

  const recognizeDocument = async (file) => {
    const fileName = file.name;
    if (fileName === "test_1.pdf") {
      return "epd1";
    } else if (fileName === "test_2.pdf") {
      return "epd2";
    } else {
      return "unknown";
    }
  };

  const extractData = async (file, documentType) => {
    let extractedData = {}; // Initialize extractedData

    if (documentType === "epd1") {
      // Placeholder extracted data for test_1.pdf
      extractedData = {
        "Solid Construction Flooring": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO2 eq",
            total: 1.51e1,
            "A1-A3": 7.55,
            A4: 1.13,
          },
          "Biogenic Carbon Removals (BCR)": {
            unit: "kg CO2",
            total: -4.3e1,
            "A1-A3": 4.1e1,
            A4: -2.05,
          },
          "Biogenic Carbon Emissions (BCE)": {
            unit: "kg CO2",
            total: 1.7e1,
            "A1-A3": 1.49e1,
            A4: 0.0,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq",
            total: 1.55e-6,
            "A1-A3": 8.26e-7,
            A4: 4.06e-8,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO2 eq",
            total: 1.19e-1,
            "A1-A3": 7.15e-2,
            A4: 6.86e-3,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq",
            total: 1.78e-1,
            "A1-A3": 2.28e-2,
            A4: 3.38e-4,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O3 eq",
            total: 2.5,
            "A1-A3": 1.84,
            A4: 2.18e-1,
          },
          "Abiotic Resource Depletion Potential (ADP)": {
            unit: "MJ surplus",
            total: 2.29e1,
            "A1-A3": 1.21e1,
            A4: 2.33,
          },
        },
        "7/16 Engineered Construction Flooring": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO2 eq",
            total: 1.31e1,
            "A1-A3": 6.85,
            A4: 5.85e-1,
          },
          "Biogenic Carbon Removals (BCR)": {
            unit: "kg CO2",
            total: -2.24e1,
            "A1-A3": -2.13e1,
            A4: 0.0,
          },
          "Biogenic Carbon Emissions (BCE)": {
            unit: "kg CO2",
            total: 8.38,
            "A1-A3": 7.34,
            A4: 0.0,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq",
            total: 1.51e-6,
            "A1-A3": 8.4e-7,
            A4: 2.11e-8,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO2 eq",
            total: 9.5e-2,
            "A1-A3": 5.3e-2,
            A4: 3.56e-3,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq",
            total: 1.21e-1,
            "A1-A3": 2.25e-2,
            A4: 1.76e-4,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O3 eq",
            total: 1.72,
            "A1-A3": 1.24,
            A4: 1.13e-1,
          },
          "Abiotic Resource Depletion Potential (ADP)": {
            unit: "MJ surplus",
            total: 2.12e1,
            "A1-A3": 1.22e1,
            A4: 1.21,
          },
        },
        "Solid 2-Ply Engineered Construction Flooring": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO2 eq",
            total: 1.9e1,
            "A1-A3": 6.87,
            A4: 9.1e-1,
          },
          "Biogenic Carbon Removals (BCR)": {
            unit: "kg CO2",
            total: -3.7e1,
            "A1-A3": -3.53e1,
            A4: 0.0,
          },
          "Biogenic Carbon Emissions (BCE)": {
            unit: "kg CO2",
            total: 1.35e1,
            "A1-A3": 1.19e1,
            A4: 0.0,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq",
            total: 2.23e-6,
            "A1-A3": 8.59e-7,
            A4: 3.28e-8,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO2 eq",
            total: 1.22e-1,
            "A1-A3": 5.71e-2,
            A4: 5.53e-3,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq",
            total: 1.52e-1,
            "A1-A3": 2.01e-2,
            A4: 2.73e-4,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O3 eq",
            total: 2.4,
            "A1-A3": 1.49,
            A4: 1.76e-1,
          },
          "Abiotic Resource Depletion Potential (ADP)": {
            unit: "MJ surplus",
            total: 3.13e1,
            "A1-A3": 1.14e1,
            A4: 1.88,
          },
        },
      };
    } else if (documentType === "epd2") {
      // Placeholder extracted data for test_2.pdf
      extractedData = {
        "Monolithic Glass (per m²)": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO₂ eq.",
            total: 3.83e1,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO₂ eq.",
            total: 1.88e-1,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq.",
            total: 1.78e-2,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq.",
            total: 2.88e-7,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O₃ eq.",
            total: 4.49,
          },
          "Abiotic Resource Depletion Potential - fossil (ADP-f)": {
            unit: "MJ Surplus",
            total: 7.8e1,
          },
          "Abiotic Resource Depletion Potential - element (ADP-e)": {
            unit: "kg Fe eq.",
            total: 3.18e-1,
          },
        },
        "Laminated Glass (per m²)": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO₂ eq.",
            total: 6.92e1,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO₂ eq.",
            total: 3.37e-1,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq.",
            total: 3.91e-2,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq.",
            total: 2.72e-7,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O₃ eq.",
            total: 7.91,
          },
          "Abiotic Resource Depletion Potential - fossil (ADP-f)": {
            unit: "MJ Surplus",
            total: 1.43e2,
          },
          "Abiotic Resource Depletion Potential - element (ADP-e)": {
            unit: "kg Fe eq.",
            total: 5.44e-1,
          },
        },
        "Sealed Units (per m²)": {
          "Global Warming Potential (GWP)": {
            unit: "kg CO₂ eq.",
            total: 7.28e1,
          },
          "Acidification Potential (AP)": {
            unit: "kg SO₂ eq.",
            total: 3.59e-1,
          },
          "Eutrophication Potential (EP)": {
            unit: "kg N eq.",
            total: 4.08e-2,
          },
          "Ozone Depletion Potential (ODP)": {
            unit: "kg CFC-11 eq.",
            total: 3.94e-7,
          },
          "Smog Formation Potential (SFP)": {
            unit: "kg O₃ eq.",
            total: 8.26,
          },
          "Abiotic Resource Depletion Potential - fossil (ADP-f)": {
            unit: "MJ Surplus",
            total: 1.49e2,
          },
          "Abiotic Resource Depletion Potential - element (ADP-e)": {
            unit: "kg Fe eq.",
            total: 6.02e-1,
          },
        },
      };
    } else {
      return null;
    }

    // Add company name based on document type
    if (documentType === "epd1") {
      extractedData.companyName = "Lauzon Hardwood Flooring";
    } else if (documentType === "epd2") {
      extractedData.companyName = "Laurier Architectural INC.";
    }

    return extractedData;
  };

  return (
    <div>
      <h2 className="title">EPD Calculator</h2>

      <input type="file" onChange={handleFileChange} />
      <button className="btn btn-primary"  onClick={processEpd}>Process EPD</button>

      {isLoading && (
        <div>
          <p>Processing document... Please wait.</p>
        </div>
      )}

      {extractedData && !isLoading && (
        <div>
          {/* Display company name */}
          {extractedData.companyName && (
            <div>
              <h4 className="title" style={{ color: "red" }}>
                Company: {extractedData.companyName}
              </h4>
            </div>
          )}
          {/* Conditionally render checkboxes based on file type */}
          {recognizedDocumentType === "epd1" && (
            <div>
              <label>
                <input
                  type="checkbox"
                  checked={showSolidFlooring}
                  onChange={() => setShowSolidFlooring(!showSolidFlooring)}
                />
                Material 1: Solid Construction Flooring
              </label>

              <label>
                <input
                  type="checkbox"
                  checked={showEngineeredFlooring}
                  onChange={() =>
                    setShowEngineeredFlooring(!showEngineeredFlooring)
                  }
                />
                Material 2: 7/16 Engineered Construction Flooring
              </label>

              <label>
                <input
                  type="checkbox"
                  checked={showSolid2PlyFlooring}
                  onChange={() =>
                    setShowSolid2PlyFlooring(!showSolid2PlyFlooring)
                  }
                />
                Material 3: Solid 2-Ply Engineered Construction Flooring
              </label>
            </div>
          )}

          {recognizedDocumentType === "epd2" && (
            <div>
              <label>
                <input
                  type="checkbox"
                  checked={showMonolithicGlass}
                  onChange={() => setShowMonolithicGlass(!showMonolithicGlass)}
                />
                Monolithic Glass (per m²)
              </label>

              <label>
                <input
                  type="checkbox"
                  checked={showLaminatedGlass}
                  onChange={() => setShowLaminatedGlass(!showLaminatedGlass)}
                />
                Laminated Glass (per m²)
              </label>

              <label>
                <input
                  type="checkbox"
                  checked={showSealedUnits}
                  onChange={() => setShowSealedUnits(!showSealedUnits)}
                />
                Sealed Units (per m²)
              </label>
            </div>
          )}

          {/* Render tables based on file type */}
          {recognizedDocumentType === "epd1" &&
            Object.entries(extractedData).map(([materialGroup, data]) => {
              const showGroup =
                (showSolidFlooring &&
                  materialGroup === "Solid Construction Flooring") ||
                (showEngineeredFlooring &&
                  materialGroup === "7/16 Engineered Construction Flooring") ||
                (showSolid2PlyFlooring &&
                  materialGroup ===
                    "Solid 2-Ply Engineered Construction Flooring");

              if (showGroup) {
                return (
                  <div key={materialGroup}>
                    <h4 className="title">{materialGroup}</h4>
                    <table>
                      <thead>
                        <tr>
                          <th>Environmental Impact</th>
                          <th>Unit</th>
                          <th>Total</th>
                          <th>Production</th>
                          <th>Transportation to Site</th>
                        </tr>
                      </thead>
                      <tbody>
                        {Object.entries(data).map(([category, values]) => (
                          <tr key={category}>
                            <td>{category}</td>
                            <td>{values.unit}</td>
                            <td>{values.total}</td>
                            <td>{values["A1-A3"]}</td>
                            <td>{values.A4}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                );
              } else {
                return null;
              }
            })}

          {recognizedDocumentType === "epd2" &&
            Object.entries(extractedData).map(([materialGroup, data]) => {
              const showGroup =
                (showMonolithicGlass &&
                  materialGroup === "Monolithic Glass (per m²)") ||
                (showLaminatedGlass &&
                  materialGroup === "Laminated Glass (per m²)") ||
                (showSealedUnits && materialGroup === "Sealed Units (per m²)");

              if (showGroup) {
                return (
                  <div key={materialGroup}>
                    <h4>{materialGroup}</h4>
                    <table>
                      <thead>
                        <tr>
                          <th>Environmental Impact</th>
                          <th>Unit</th>
                          <th>Total</th>
                        </tr>
                      </thead>
                      <tbody>
                        {Object.entries(data).map(([category, values]) => (
                          <tr key={category}>
                            <td>{category}</td>
                            <td>{values.unit}</td>
                            <td>{values.total}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                );
              } else {
                return null;
              }
            })}
        </div>
      )}
    </div>
  );
}

export default EpdCalculator;
